package net.lzzy.practices.web.course;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ser.std.UUIDSerializer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.lzzy.practices.constants.ApiConstants;
import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.entities.Result;
import net.lzzy.practices.entities.User;
import net.lzzy.practices.services.ResultService;
import net.lzzy.practices.utils.AuthUtils;
import net.lzzy.practices.utils.StringUtils;
import net.lzzy.practices.web.models.ApiResult;
import net.lzzy.practices.web.models.OptionKeyInfo;
import net.lzzy.practices.web.models.VmResult;
import org.hibernate.cfg.annotations.ResultsetMappingSecondPass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * @author liaodcc on 2022/6/8 16:16.
 */
@Api(tags = "提交结果相关业务")
@CrossOrigin
@RestController
@RequestMapping(ApiConstants.ROUTE_RESULT_ROOT)
public class ResultApiController {
    private final ResultService service;

    @Autowired
    public ResultApiController(ResultService service) {
        this.service = service;
    }

    @PostMapping(ApiConstants.ROUTE_RESULT_POST)
    @ApiOperation(value = "某学生提交某一章节的所有题目",notes = "token(String)<br/>")
    public ApiResult postResult (@RequestBody JSONObject json){
        String token = json.getString(ApiConstants.KEY_TOKEN);
        if (StringUtils.isEmpty(token)){
            return new ApiResult(false, Messages.NO_PERMISSION.toString(), null);
        }
        JSONArray array = json.getJSONArray(ApiConstants.KEY_RESULT_OPTION_ARRAY);
        if (array == null){
            return new ApiResult(false,Messages.INCOMPLETE_INFO.toString(), null);
        }
        List<VmResult> results = new ArrayList<>();
        for (int i = 0; i < array.size();i++){
            JSONObject jo = array.getJSONObject(i);
            String strQuestionId = jo.getString(ApiConstants.KEY_RESULT_OPTION_QUESTION_ID);
            JSONArray arrOptions = jo.getJSONArray(ApiConstants.KEY_RESULT_OPTION_ID);
            UUID questionId = UUID.fromString(strQuestionId);
            List<UUID> optionIds = new ArrayList<>();
            arrOptions.forEach(o -> optionIds.add(UUID.fromString(o.toString())));
            results.add(new VmResult(service.add(questionId,optionIds,token)));
        }
        return new ApiResult(true,results.size() + "",results);
    }

    @DeleteMapping(ApiConstants.ROUTE_RESULT_DEL)
    @ApiOperation(value = "删除某一提交的结果",notes = "1.token(String)<br/>2.strResultId(String)<br/>")
    public ApiResult remove(@RequestBody OptionKeyInfo info){
        String token = info.getToken();
        String strResultId = info.getOptionId();
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(strResultId)){
            return new ApiResult(false,Messages.INCOMPLETE_INFO.toString(), null);
        }
        UUID resultId = UUID.fromString(strResultId);
        Messages msg = service.remove(resultId,token);
        return new ApiResult(msg == Messages.SUCCESS,msg.toString(),null);
    }

    @DeleteMapping(ApiConstants.ROUTE_RESULT_CHAPTER_DEL)
    @ApiOperation(value = "删除某一章节的结果" ,notes = "1.token(String)<br/>2.strResultId(String)<br/>")
    public ApiResult removeChapter(@RequestBody OptionKeyInfo info){
        String token = info.getToken();
        String strChapterId = info.getOptionId();
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(strChapterId)){
            return new ApiResult(false,Messages.INCOMPLETE_INFO.toString(), null);
        }
        UUID chapterId = UUID.fromString(strChapterId);
        Messages msg = service.removeChapter(chapterId,token);
        return new ApiResult(msg == Messages.SUCCESS,msg.toString(),null);
    }

    @GetMapping(ApiConstants.ROUTE_RESULT_CHAPTER)
    @ApiOperation(value = "获取某学生某个章节的所有题目结果" ,notes = "1.id(UUID)<br/>2.id(UUID)<br/>3.token(String)")
    public ApiResult getChapterResult(@RequestParam(name = "sid") UUID studentId,
                                      @RequestParam(name = "cid") UUID chapterId,
                                      @RequestParam String token){
        if (AuthUtils.illegalUser(token,new int[]{User.TYPE_STUDENT})){
            return new ApiResult(false,Messages.NO_PERMISSION.toString(), null);
        }
        List<VmResult>results = new ArrayList<>();
        service.getChapterResults(studentId,chapterId).forEach(result -> results.add(new VmResult(result)));
        return new ApiResult(true,results.size() + "",results);
    }

    @GetMapping(ApiConstants.ROUTE_RESULT_QUESTION)
    @ApiOperation(value = "教师获取某个题目所有学生提交的结果" ,notes = "1.id(UUID)<br/>2.id(UUID)<br/>3.token(String)")
    public ApiResult getQuestionResults(@RequestParam(name = "qid") UUID questionId,
                                        @RequestParam String token){
        List<VmResult> results = new ArrayList<>();
        List<Result> list = service.getQuestionResults(questionId,token);
        if (list == null){
            return new ApiResult(false,Messages.WRONG_ID + "或" +Messages.NO_PERMISSION,null);
        }
        list.forEach(result -> results.add(new VmResult(result)));
        return new ApiResult(true,results.size() + "",results);
    }

    @GetMapping(ApiConstants.ROUTE_RESULT_COMMITTED)
    @ApiOperation(value = "判断某章节某学生是否已提交答案" ,notes = "1.id(UUID)<br/>2.id(UUID)<br/>3.token(String)")
    public ApiResult isChapterCommitted(@RequestParam(name = "sid") UUID studentId,
                                        @RequestParam(name = "cid") UUID chapterId,
                                        @RequestParam String token){
        Boolean result = service.isChapterCommitted(studentId,chapterId,token);
        String message = result == null ? Messages.NO_PERMISSION.toString() : "";
        return new ApiResult(true,message,result);
    }
}
